package cn.zhbitzwz.com.testappbyid;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.List;

import cn.zhbitzwz.com.testappbyid.Adapter.AppAdapter;
import cn.zhbitzwz.com.testappbyid.Adapter.AppPickerAdapter;
import cn.zhbitzwz.com.testappbyid.Adapter.LocationPickerAdapter;
import cn.zhbitzwz.com.testappbyid.Adapter.WifiPickerAdapter;
import cn.zhbitzwz.com.testappbyid.AppList.Appinfo;
import cn.zhbitzwz.com.testappbyid.AppList.Appinfomain;
import cn.zhbitzwz.com.testappbyid.MyBean.AppPicker;
import cn.zhbitzwz.com.testappbyid.MyBean.LocationPicker;
import cn.zhbitzwz.com.testappbyid.MyBean.WifiPicker;
import cz.msebera.android.httpclient.Header;


public class MainActivity extends AppCompatActivity {
    //布局
    View olderSelectView = null;
    private ListView listViewShow;
    private ArrayAdapter<String> adapter;

    private ListAdapter adapterShow;
    //控件
    private Button btnConfirm;
    private TextView view;
    private Spinner spinnerAppPicker;
    private Spinner spinnerLocationPicker;
    private Spinner spinnerWifiPicker;
    private Spinner spinnerPackagePicker;

    private List<AppPicker> appPickers = new ArrayList<AppPicker>();
    private List<AppPicker> packagePickers = new ArrayList<AppPicker>();
    private List<LocationPicker> locationPickers = new ArrayList<LocationPicker>();
    private List<WifiPicker> wifiPickers = new ArrayList<WifiPicker>();

    private AppPickerAdapter appPickerAdapter;
    private AppPickerAdapter packagePickerAdapter;
    private LocationPickerAdapter locationPickerAdapter;
    private WifiPickerAdapter wifiPickerAdapter;

    private String appOpen = null;
    private String location = null;
    private String wifi = null;
    private String apppackage = null;

    private CheckBox checkBoxBluetooth;
    private CheckBox checkBoxDataConn;
    private CheckBox checkBoxCharge;
    private CheckBox checkBoxAudio;

    private Boolean bluetooth = false;
    private Boolean dataConn = false;
    private Boolean charge = false;
    private Boolean audio = false;

    //外部调用控件
    NotificationBroadcastReceiver mReceiver;

    //返回的数据
    private String resultData;
    private List<String> resultList = new ArrayList<String>();
    //Action
    public final static String ACTION_BTN = "cn.zhbitzwz.com.testappbyid.btn.login";

    public final static String INTENT_NAME = "btnid";

    public final static int INTENT_BTN_LOGIN = 1;

    public static Drawable notificationShowDrawable = null;

    public final Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                //show APP
                showAppResult(msg.obj);
            }
        }
    };
    private void initPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW}, 1);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initialView();
        //Initial Picker Data
        initialData();

        Button button1 = (Button) findViewById(R.id.btn_appinfo);
        button1.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, Appinfomain.class);
                startActivity(intent);
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(!Settings.canDrawOverlays(getApplicationContext())) {
                //启动Activity让用户授权
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent,100);
            }
        }

        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Get Data
                netPredictData();
            }
        });
        setfloadwindow();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(this)) {
                    WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
                    WindowManager.LayoutParams params = new WindowManager.LayoutParams();
                    params.type = WindowManager.LayoutParams.TYPE_PHONE;
                    params.format = PixelFormat.RGBA_8888;
                    windowManager.addView(view, params);
                } else {
                    Toast.makeText(this, "ACTION_MANAGE_OVERLAY_PERMISSION权限已被拒绝", Toast.LENGTH_SHORT).show();
                    ;
                }
            }

        }
    }

    public void setfloadwindow()
    {
        int[] images={R.mipmap.browser,R.mipmap.googleplay,R.mipmap.home,R.mipmap.qq,R.mipmap.setting};
        HorizontalScrollView l1=new HorizontalScrollView(this);
        LinearLayout l2=new LinearLayout(this);
        l1.addView(l2);
        ImageView image1=new ImageView(this);
        ImageView image2=new ImageView(this);
        ImageView image3=new ImageView(this);
        ImageView image4=new ImageView(this);
        ImageView image5=new ImageView(this);
        ImageView [] imagelist={image1,image2,image3,image4,image5};
        for(int i=0 ; i<imagelist.length;i++) {
            imagelist[i].setImageResource(images[i]);
            l2.addView(imagelist[i]);
        }
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                0, 0,
                PixelFormat.TRANSPARENT
        );
        layoutParams.flags= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
        // type 设置 Window 类别（层级）
        layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
        layoutParams.gravity = Gravity.TOP;
        layoutParams.x=30;
        layoutParams.y=110;
        WindowManager windowManager = getWindowManager();
        windowManager.addView(l1, layoutParams);
        l1.setBackgroundColor(Color.parseColor("#CFCFCF"));
    }
    private void showAppResult(Object obj) {
        //        btnStart.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //TODO 启动外部APP代码
//                Intent intent = getPackageManager().getLaunchIntentForPackage("com.zhbitzwz.vehiclesystems");
//                if (intent == null) {
//                    Toast.makeText(MainActivity.this, "请安装相应的应用程序", Toast.LENGTH_LONG).show();
//                } else {
//                    String post_data = "post_data";
//                    //intent显示传入数据
//                    intent.putExtra("zhouweizhi<<", post_data);
//                    startActivity(intent);
//                }
//            }
//        });
//        btnEnd.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Toast.makeText(MainActivity.this, "点击停止按钮", Toast.LENGTH_LONG).show();
//            }
//        });


        //TODO 获取已安装应用信息(图标，名称，版本号，包)
        ArrayList<AppInfo> appList = new ArrayList<AppInfo>(); //用来存储获取的应用信息数据
        List<PackageInfo> packages = getPackageManager().getInstalledPackages(0);

        //TODO 遍历判断app的包名与网络请求回调结果比较
        String[] split = (obj.toString()).split("\\s+");
        for (String each : split) {
            resultList.add(each);
        }

        System.out.println(resultList);

        for (String s : resultList) {

            for (int i = 0; i < packages.size(); i++) {
                PackageInfo packageInfo = packages.get(i);
                AppInfo tmpInfo = new AppInfo();

                tmpInfo.appName = packageInfo.applicationInfo.loadLabel(getPackageManager()).toString();
                tmpInfo.packageName = packageInfo.packageName;
                tmpInfo.versionName = packageInfo.versionName;
                tmpInfo.versionCode = packageInfo.versionCode;
                tmpInfo.appIcon = packageInfo.applicationInfo.loadIcon(getPackageManager());

                Log.i("APP ALL Info<<<", tmpInfo.toString());

                if (s.equals(packageInfo.packageName)) {
                    appList.add(tmpInfo);
                    break;
                }
            }

        }
//                switch (packageInfo.packageName) {
//                    case "com.tencent.mm":
//                    case "com.tencent.mobileqq":
//                    case "com.sina.weibo":
//                    case "com.baidu.tieba":
//                    case "com.android.mms":
//                    case "com.android.settings":
//                    case "com.supercell.clashroyale":
//                    case "com.android.alarmclock":
//                    case "com.android.browser":
//                    case "com.google.android.gms":
//                        appList.add(tmpInfo);
//                        break;
//                    default:
//            }
        //为Notification创建一个icon
//            if ("com.moresmart.litme2".equals(packageInfo.packageName)) {
//                notificationShowDrawable = packageInfo.applicationInfo.loadIcon(getPackageManager());
//            }
        for (int i = 0; i < appList.size(); i++) {
            Log.i("APP CHOOSE INFO<<", appList.get(i).toString());
        }
        AppAdapter appAdapter = new AppAdapter(MainActivity.this, appList);

        listViewShow.setDividerHeight(5);
        if (listViewShow != null) {
            listViewShow.setAdapter(appAdapter);
        }
        //TODO Notification 通知栏显示信息
//        btnNotification.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                notification();
//            }
//        });
        resultList = new ArrayList<>(); // 重置

    }

    private void netPredictData() {
        final AsyncHttpClient client = new AsyncHttpClient();
        final String url = "http://10.42.0.1:8080/api/apps/list";
        final RequestParams params = new RequestParams();

        params.put("appOpen", appOpen);
        params.put("location", location);
        params.put("wifi", wifi);
        params.put("dataConn", dataConn ? "1" : "0");
        params.put("charge", charge ? "1" : "0");
        params.put("audio", audio ? "1" : "0");
        params.put("blueTooth", bluetooth ? "1" : "0");
        params.put("package", apppackage);
        client.setTimeout(6000); // for 60s

        client.get(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                Toast.makeText(MainActivity.this, url, Toast.LENGTH_SHORT).show();
                Toast.makeText(MainActivity.this, params.toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String response = new String(responseBody);
//                System.out.println(response);
//                JSONObject object = null;
//                try {
//                    object = new JSONObject(response);
////                    int status = object.getInt("status");
////                    if (status == 0){
////                        Toast.makeText(MainActivity.this, object.getString("msg"), Toast.LENGTH_SHORT).show();
////                    } else {
////                        resultData = object.getString("app");
//                    resultData = object.getString("app");
//                    Message message = new Message();
//                    message.what = 1;
//                    message.obj = resultData;
//                    mHandle.sendMessage(message);
////                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
                Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
                Message message = new Message();
                message.what = 1;
                message.obj = response;
                mHandle.sendMessage(message);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initialData() {
        appPickers.add(new AppPicker("微信", "com.tencent.mm"));
        appPickers.add(new AppPicker("QQ", "com.tencent.mobileqq"));
        appPickers.add(new AppPicker("微博", "com.sina.weibo"));
        appPickers.add(new AppPicker("贴吧", "com.baidu.tieba"));
        appPickers.add(new AppPicker("短信", "com.android.mms"));
        appPickers.add(new AppPicker("设置", "com.android.settings"));
        appPickers.add(new AppPicker("皇室战争", "com.supercell.clashroyale"));
        appPickers.add(new AppPicker("闹钟", "com.android.alarmclock"));
        appPickers.add(new AppPicker("浏览器", "com.android.browser"));
        appPickers.add(new AppPicker("Google Play", "com.google.android.gms"));

        packagePickers.add(new AppPicker("微信", "com.tencent.mm"));
        packagePickers.add(new AppPicker("QQ", "com.tencent.mobileqq"));
        packagePickers.add(new AppPicker("微博", "com.sina.weibo"));
        packagePickers.add(new AppPicker("贴吧", "com.baidu.tieba"));
        packagePickers.add(new AppPicker("短信", "com.android.mms"));
        packagePickers.add(new AppPicker("设置", "com.android.settings"));
        packagePickers.add(new AppPicker("皇室战争", "com.supercell.clashroyale"));
        packagePickers.add(new AppPicker("闹钟", "com.android.alarmclock"));
        packagePickers.add(new AppPicker("浏览器", "com.android.browser"));
        packagePickers.add(new AppPicker("Google Play", "com.google.android.gms"));

        locationPickers.add(new LocationPicker("学校", "school"));
        locationPickers.add(new LocationPicker("家", "home"));
        locationPickers.add(new LocationPicker("其他", "else"));

        wifiPickers.add(new WifiPicker("zhbitNet", "zhbitNet"));
        wifiPickers.add(new WifiPicker("home", "home"));

        appPickerAdapter = new AppPickerAdapter(appPickers, this);
        packagePickerAdapter = new AppPickerAdapter(packagePickers, this);

        locationPickerAdapter = new LocationPickerAdapter(locationPickers, this);
        wifiPickerAdapter = new WifiPickerAdapter(wifiPickers, this);

        spinnerAppPicker.setAdapter(appPickerAdapter);
        spinnerPackagePicker.setAdapter(packagePickerAdapter);
        spinnerWifiPicker.setAdapter(wifiPickerAdapter);
        spinnerLocationPicker.setAdapter(locationPickerAdapter);

        //获取数据
        spinnerAppPicker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        Toast.makeText(MainActivity.this, "com.tencent.mm", Toast.LENGTH_SHORT).show();
                        appOpen = "com.tencent.mm";
                        break;
                    case 1:
                        Toast.makeText(MainActivity.this, "com.tencent.mobileqq", Toast.LENGTH_SHORT).show();
                        appOpen = "com.tencent.mobileqq";
                        break;
                    case 2:
                        Toast.makeText(MainActivity.this, "com.sina.weibo", Toast.LENGTH_SHORT).show();
                        appOpen = "com.sina.weibo";
                        break;
                    case 3:
                        Toast.makeText(MainActivity.this, "com.baidu.tieba", Toast.LENGTH_SHORT).show();
                        appOpen = "com.baidu.tieba";
                        break;
                    case 4:
                        Toast.makeText(MainActivity.this, "com.android.settings", Toast.LENGTH_SHORT).show();
                        appOpen = "com.android.settings";
                        break;
                    case 5:
                        Toast.makeText(MainActivity.this, "com.android.mms", Toast.LENGTH_SHORT).show();
                        appOpen = "com.android.mms";
                        break;
                    case 6:
                        Toast.makeText(MainActivity.this, "com.supercell.clashroyale", Toast.LENGTH_SHORT).show();
                        appOpen = "com.supercell.clashroyale";
                        break;
                    case 7:
                        Toast.makeText(MainActivity.this, "com.android.alarmclock", Toast.LENGTH_SHORT).show();
                        appOpen = "com.android.alarmclock";
                        break;
                    case 8:
                        Toast.makeText(MainActivity.this, "com.android.browser", Toast.LENGTH_SHORT).show();
                        appOpen = "com.android.browser";
                        break;
                    case 9:
                        Toast.makeText(MainActivity.this, "com.google.android.gms", Toast.LENGTH_SHORT).show();
                        appOpen = "com.google.android.gms";
                        break;
                    default:
                        Toast.makeText(MainActivity.this, "请选择AppPicker", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(MainActivity.this, "请选择AppPicker", Toast.LENGTH_SHORT).show();
            }
        });

        spinnerPackagePicker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        Toast.makeText(MainActivity.this, "com.tencent.mm", Toast.LENGTH_SHORT).show();
                        apppackage = "com.tencent.mm";
                        break;
                    case 1:
                        Toast.makeText(MainActivity.this, "com.tencent.mobileqq", Toast.LENGTH_SHORT).show();
                        apppackage = "com.tencent.mobileqq";
                        break;
                    case 2:
                        Toast.makeText(MainActivity.this, "com.sina.weibo", Toast.LENGTH_SHORT).show();
                        apppackage = "com.sina.weibo";
                        break;
                    case 3:
                        Toast.makeText(MainActivity.this, "com.baidu.tieba", Toast.LENGTH_SHORT).show();
                        apppackage = "com.baidu.tieba";
                        break;
                    case 4:
                        Toast.makeText(MainActivity.this, "com.android.settings", Toast.LENGTH_SHORT).show();
                        apppackage = "com.android.settings";
                        break;
                    case 5:
                        Toast.makeText(MainActivity.this, "com.android.mms", Toast.LENGTH_SHORT).show();
                        apppackage = "com.android.mms";
                        break;
                    case 6:
                        Toast.makeText(MainActivity.this, "com.supercell.clashroyale", Toast.LENGTH_SHORT).show();
                        apppackage = "com.supercell.clashroyale";
                        break;
                    case 7:
                        Toast.makeText(MainActivity.this, "com.android.alarmclock", Toast.LENGTH_SHORT).show();
                        apppackage = "com.android.alarmclock";
                        break;
                    case 8:
                        Toast.makeText(MainActivity.this, "com.android.browser", Toast.LENGTH_SHORT).show();
                        apppackage = "com.android.browser";
                        break;
                    case 9:
                        Toast.makeText(MainActivity.this, "com.google.android.gms", Toast.LENGTH_SHORT).show();
                        apppackage = "com.google.android.gms";
                        break;
                    default:
                        Toast.makeText(MainActivity.this, "请选择packagePicker", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(MainActivity.this, "请选择packagePicker", Toast.LENGTH_SHORT).show();
            }
        });
        spinnerLocationPicker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        Toast.makeText(MainActivity.this, "school", Toast.LENGTH_SHORT).show();
                        location = "school";
                        break;
                    case 1:
                        Toast.makeText(MainActivity.this, "home", Toast.LENGTH_SHORT).show();
                        location = "home";
                        break;
                    case 2:
                        Toast.makeText(MainActivity.this, "else", Toast.LENGTH_SHORT).show();
                        location = "else";
                        break;
                    default:
                        Toast.makeText(MainActivity.this, "请选择LocationPicker", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(MainActivity.this, "请选择LocationPicker", Toast.LENGTH_SHORT).show();
            }
        });

        spinnerWifiPicker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        Toast.makeText(MainActivity.this, "school", Toast.LENGTH_SHORT).show();
                        wifi = "school";
                        break;
                    case 1:
                        Toast.makeText(MainActivity.this, "home", Toast.LENGTH_SHORT).show();
                        wifi = "home";
                        break;
                    default:
                        Toast.makeText(MainActivity.this, "请选择WifiPicker", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(MainActivity.this, "请选择WifiPicker", Toast.LENGTH_SHORT).show();
            }
        });
        checkBoxBluetooth.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(MainActivity.this, "1", Toast.LENGTH_SHORT).show();
                    bluetooth = true;
                } else {
                    Toast.makeText(MainActivity.this, "0", Toast.LENGTH_SHORT).show();
                    bluetooth = false;

                }
            }
        });
        checkBoxDataConn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(MainActivity.this, "1", Toast.LENGTH_SHORT).show();
                    dataConn = true;
                } else {
                    Toast.makeText(MainActivity.this, "0", Toast.LENGTH_SHORT).show();
                    dataConn = false;

                }
            }
        });
        checkBoxCharge.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(MainActivity.this, "1", Toast.LENGTH_SHORT).show();
                    charge = true;
                } else {
                    Toast.makeText(MainActivity.this, "0", Toast.LENGTH_SHORT).show();
                    charge = false;

                }
            }
        });
        checkBoxAudio.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(MainActivity.this, "1", Toast.LENGTH_SHORT).show();
                    audio = true;
                } else {
                    Toast.makeText(MainActivity.this, "0", Toast.LENGTH_SHORT).show();
                    audio = false;

                }
            }
        });

    }

    private void initialView() {
        listViewShow = (ListView) findViewById(R.id.lv_show);
        spinnerAppPicker = (Spinner) findViewById(R.id.spinner_app_piker);
        spinnerPackagePicker = (Spinner) findViewById(R.id.spinner_package_piker);
        spinnerLocationPicker = (Spinner) findViewById(R.id.spinner_location_piker);
        spinnerWifiPicker = (Spinner) findViewById(R.id.spinner_wifi_piker);

        checkBoxBluetooth = (CheckBox) findViewById(R.id.checkBox_bluetooth);
        checkBoxDataConn = (CheckBox) findViewById(R.id.checkBox_dataconn);
        checkBoxCharge = (CheckBox) findViewById(R.id.checkBox_charge);
        checkBoxAudio = (CheckBox) findViewById(R.id.checkBox_audio);

        btnConfirm = (Button) findViewById(R.id.btn_confirm);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregeisterReceiver();
    }

    //通知栏测试
    private void notification() {
        unregeisterReceiver();
        intiReceiver();

        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification);
        remoteViews.setTextViewText(R.id.tv_up, "com.zhbitzwz.cn");//标题 => 包名
        remoteViews.setTextViewText(R.id.tv_down, "APP预测");//子标题 => APP名字
        //点击的事件处理
        Intent intent = new Intent(ACTION_BTN);//事件包名
        intent.putExtra(INTENT_NAME, INTENT_BTN_LOGIN);//标签和动作
        //这里加了广播，所及INTENT的必须用getBroadcast方法
        PendingIntent intentpi = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.btn_login, intentpi);//绑定控件

        Intent intent2 = new Intent();
        intent2.setClass(this, MainActivity.class);
        intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent intentContent = PendingIntent.getActivity(this, 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);


        //配置Notification风格
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setOngoing(true);
        builder.setAutoCancel(false);
        builder.setTicker("正在使用APP预测");
        builder.setSmallIcon(R.drawable.id_airport);//设置Icon
        builder.setContent(remoteViews);
        builder.setWhen(System.currentTimeMillis());// 通知产生的时间，会在通知信息里显示
//                .setTicker("正在播放")
//        builder.setPriority(Notification.PRIORITY_DEFAULT);// 设置该通知优先级
//                .setOngoing(true)
//                .setSmallIcon(R.drawable.sing_icon);

        Notification notification = builder.build();
        notification.defaults = Notification.DEFAULT_SOUND;
        notification.flags = Notification.FLAG_NO_CLEAR;
        notification.contentIntent = intentContent;

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notification);

    }

    private void intiReceiver() {
        mReceiver = new NotificationBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_BTN);
        getApplicationContext().registerReceiver(mReceiver, intentFilter);
    }

    private void unregeisterReceiver() {
        if (mReceiver != null) {
            getApplicationContext().unregisterReceiver(mReceiver);
            mReceiver = null;
        }
    }


    class NotificationBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_BTN)) {
                int btn_id = intent.getIntExtra(INTENT_NAME, 0);
                switch (btn_id) {
                    case INTENT_BTN_LOGIN:
                        Toast.makeText(MainActivity.this, "从通知栏点登录", Toast.LENGTH_SHORT).show();
                        unregeisterReceiver();
                        NotificationManager notificationManager = (NotificationManager) MainActivity.this.getSystemService(Context.NOTIFICATION_SERVICE);
                        notificationManager.cancel(0);
                        break;
                }
            }
        }
    }
}
